package com.atguigu.srb.core.service.impl;

import com.atguigu.srb.core.enums.UserBindEnum;
import com.atguigu.srb.core.exception.Assert;
import com.atguigu.srb.core.hfb.FormHelper;
import com.atguigu.srb.core.hfb.HfbConst;
import com.atguigu.srb.core.hfb.RequestHelper;
import com.atguigu.srb.core.mapper.UserInfoMapper;
import com.atguigu.srb.core.pojo.entity.UserBind;
import com.atguigu.srb.core.mapper.UserBindMapper;
import com.atguigu.srb.core.pojo.entity.UserInfo;
import com.atguigu.srb.core.pojo.vo.UserBindVO;
import com.atguigu.srb.core.result.ResponseEnum;
import com.atguigu.srb.core.service.UserBindService;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 用户绑定表 服务实现类
 * </p>
 *
 * @author AtLong
 * @since 2022-06-11
 */
@Service
public class UserBindServiceImpl extends ServiceImpl<UserBindMapper, UserBind> implements UserBindService {
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Override
    public String commitBindUser(UserBindVO userBindVO, Long userId) {
        // 用户是否绑定过身份证
        QueryWrapper<UserBind> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("id_card", userBindVO.getIdCard())
                .ne("user_id", userId);
        UserBind userBind = baseMapper.selectOne(queryWrapper);
        Assert.isNull(userBind, ResponseEnum.USER_BIND_IDCARD_EXIST_ERROR);

        // 用户是否绑定过表单
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id", userId);
        userBind = baseMapper.selectOne(queryWrapper);

        if (ObjectUtils.isEmpty(userBind)) {
            // 创建用户绑定记录
            userBind = new UserBind();
        /*userBind.setBankNo(userBindVO.getBankNo());
        userBind.setBankType(userBindVO.getBankType());
        userBind.setIdCard(userBindVO.getIdCard());
        userBind.setUserId(userId);*/
            BeanUtils.copyProperties(userBindVO, userBind);
            userBind.setUserId(userId);
            userBind.setStatus(UserBindEnum.NO_BIND.getStatus());
            baseMapper.insert(userBind);
        } else {
            // 曾经跳转到托管平台，但是未操作完成，此时将用户最新填写的数据同步到userBind对象
            BeanUtils.copyProperties(userBindVO, userBind);
            baseMapper.updateById(userBind);
        }

        // 生成动态表单字符串
        String url = HfbConst.USERBIND_URL;
        Map<String, Object> map = new HashMap<>();
        map.put("agentId", HfbConst.AGENT_ID);
        map.put("agentUserId", userId);
        map.put("idCard", userBindVO.getIdCard());
        map.put("personalName", userBindVO.getName());
        map.put("bankType", userBindVO.getBankType());
        map.put("bankNo", userBindVO.getBankNo());
        map.put("mobile", userBindVO.getMobile());
        map.put("email", userBindVO.getMobile());
        map.put("returnUrl", HfbConst.USERBIND_RETURN_URL);
        map.put("notifyUrl", HfbConst.USERBIND_NOTIFY_URL);
        map.put("timestamp", RequestHelper.getTimestamp());
        map.put("sign", RequestHelper.getSign(map));
        // 调用工具类构建方法
        String formStr = FormHelper.buildForm(url, map);

        return formStr;
    }

    @Transactional(rollbackFor = RuntimeException.class) // 事务处理
    @Override
    public void  asyncNotify(Map<String, Object> paramMap) {
        /**
         * {"agentUserId":"7",
         * "resultCode":"0001",
         * "sign":"e60bbf35ef5bcaa37617998ed12c5531",
         * "bindCode":"5daa3bc4a712462b845c7c6ad73fe67d",
         * "resultMsg":"成功",
         * "timestamp":"1656406823770"}
         */
        String bandCode = (String) paramMap.get("bindCode");
        String agentUserId = (String) paramMap.get("agentUserId");
        // 条件封装查询
        QueryWrapper<UserBind> userBindQueryWrapper = new QueryWrapper<>();
        userBindQueryWrapper.eq("user_id", agentUserId);
        // 更新用户绑定表
        UserBind userBind = baseMapper.selectOne(userBindQueryWrapper);
        userBind.setBindCode(bandCode);
        userBind.setStatus(UserBindEnum.BIND_OK.getStatus());
        baseMapper.updateById(userBind);
        // 更新用户信息表
        UserInfo userInfo = userInfoMapper.selectById(agentUserId);
        userInfo.setBindCode(bandCode);
        userInfo.setName(userBind.getName());
        userInfo.setNickName(userBind.getName());
        userInfo.setIdCard(userBind.getIdCard());
        userInfo.setBindStatus(UserBindEnum.BIND_OK.getStatus());
        userInfoMapper.updateById(userInfo);
    }
}
